﻿using System.Web.Mvc;
using WebApp.Services;
using WebApp.Classes;
using Models.Models;
using System;

namespace WebApp.Controllers
{
    [Authorize]
    public class StoreController : Controller
    {
        public ActionResult StoreManagement(long? id, bool hideRevoked = false)
        {
            var user = new UserCookie().Get().User;
            var model = new StoreService().GetStoreListByUser(user, hideRevoked).StoreList;

            ViewBag.hideRevoked = hideRevoked;
            ViewBag.storeId = id.HasValue ? id : 0;

            return View(model);
        }

        public PartialViewResult EditViewStore(long? id)
        {
            var model = new Store();

            if (id != null && id > 0)
            {
                model = new StoreService().GetStore(new Store() { ID = (long)id }).Store;
            }

            return PartialView("EditStorePartial", model);
        }

        [HttpPost]
        public ActionResult EditStore(Store model)
        {
            if (ModelState.IsValid)
            {
                var cookie = new UserCookie().Get().User;
                model.UserUpdated = cookie.UserID;

                var response = new StoreService().UpdateStore(model);

                if (response.ErrorNumber > 0)
                {
                    return JavaScript(Statics.GetWarningWindow(response.ErrorMessage));
                }
            }
            else
            {
                return JavaScript(Statics.GetWarningWindow("The form you're trying to submit containts validation errors!"));
            }

            return JavaScript(String.Format("window.location.href='{0}{1}/{2}'", this.HttpContext.Request.ApplicationPath, "/Store/StoreManagement", model.ID));
        }

        public ActionResult AddStore(long id)
        {
            var model = new StoreService().AddStore(new Store() { ParentID = id, ContractExpirationDate = DateTime.Now });

            return RedirectToAction("StoreManagement", new { id = model.Store.ID });
        }

        public ActionResult Revoke(long id)
        {
            var cookie = new UserCookie().Get().User;
            var response = new StoreService().ChangeStoreStatus(new Store() { ID = id, UserUpdated = cookie.UserID, RevokeStatus = true });

            return RedirectToAction("StoreManagement", new { id = id });
        }

        public ActionResult Activate(long id)
        {
            var cookie = new UserCookie().Get().User;
            var response = new StoreService().ChangeStoreStatus(new Store() { ID = id, UserUpdated = cookie.UserID, RevokeStatus = false });

            return RedirectToAction("StoreManagement", new { id = id });
        }
    }
}
